package app.r_teenus.frontend.controller;


import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import app.r_teenus.backend.model.Person;


@Component
public class PersonValidator {

    /**
     * Spring Web Flow activated validation (validate + ${state}).
     * Validates 'personForm' view state after binding to person.
     */
    public void validatePersonForm(Person person, MessageContext context) {
    	if (!StringUtils.hasText(person.getFirstName())){
    		context.addMessage(new MessageBuilder().error().source("firstName").code("person.form.firstName.error").build());
    	}
        if (StringUtils.hasText(person.getBirthDateString())) {
			try {
				SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
				df.setLenient(false);
				person.setBirthDate(df.parse(person.getBirthDateString()));
			} catch (ParseException e) {
				context.addMessage(new MessageBuilder().error().source("birthday").code("person.form.birthday.error").build());
			}
        }
    }
}
